package pers.burgess.fsm.server.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public final class FileUtil {
	
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm");
	
	private FileUtil() {}
	
	public static boolean copyFile(File file, File targetPath) throws IOException {
        if (file == null || targetPath == null) {
            return false;
        }
        if (!file.exists()) {
            return false;
        }
        File targetFile = new File(targetPath, file.getName());
        if (file.isDirectory()) {
            if (!targetFile.exists() && !targetFile.mkdirs()) {
                return false;
            }
            for(File innerFile: file.listFiles()) {
                copyFile(innerFile, targetFile);
            }
        } else {
            if (!targetFile.exists() && !targetFile.createNewFile()) {
                return false;
            }
            FileInputStream fis = new FileInputStream(file);
            FileOutputStream fos = new FileOutputStream(targetFile);
            int len = -1;
            byte[] buffer = new byte[2048];
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fis.close();
            fos.close();
        }
        return true;
    }
	
	public static String getDirInfos (File dictionary) {
		StringBuilder stringBuilder = new StringBuilder();
		if (dictionary.isDirectory()) {
			for (File file: dictionary.listFiles()) {
				stringBuilder.append(StringUtil.padLeft(df.format(new Date(file.lastModified())), 20));
				stringBuilder.append(StringUtil.padLeft(file.isDirectory() ? "<DIRE>" : "<FILE>", 10));
				stringBuilder.append(StringUtil.padLeft(file.getName(), 50));
				stringBuilder.append("\n");
			}
		}
		return stringBuilder.toString();
	}
	
	public static boolean deleteSingle (File file) {
		if (file == null || !file.exists())
			return false;
		if (file.isDirectory()) {
			if (file.listFiles().length > 0)
				return false;
		}
		return file.delete();
	}
	
	public static boolean deleteAll (File file) {
        if (file == null || !file.exists())
            return false;
        if (file.isDirectory()) {
            for (File f: file.listFiles()) {
                deleteAll(f);
            }
        }
        deleteSingle(file);
        return true;
    }

}
